package by.grsu.pochebut.webpage.car;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.pochebut.entity.Car;
import by.grsu.pochebut.interf.InterfCar;
import by.grsu.pochebut.webpage.MyPage;

public class EditCarPage extends MyPage {

	@SpringBean
	private InterfCar daoCar;

	@SuppressWarnings("serial")
	public EditCarPage(final Car carToEdit) {
		super();

		// create form fields and set data
		final TextField<String> modelField = new TextField<String>("model", new Model<String>(carToEdit.getModel()));
		final TextField<String> colorField=new TextField<String>("color",new Model<String>(carToEdit.getColor()));
		final TextField<Double> priceField=new TextField<Double>("price",new Model<Double>(carToEdit.getPrice()));
		priceField.setType(Double.class);
		
		// create "form" component which is required for data retrieving from
		// client to server
		Form<Car> form = new Form<Car>("form", new Model<Car>(carToEdit)) {
			@Override
			public void onSubmit() {
				// retrieve data from the form and set it to the object
				carToEdit.setModel(modelField.getModelObject());
				carToEdit.setColor(colorField.getModelObject());
				carToEdit.setPrice(priceField.getModelObject());
				carToEdit.setData();
				
				// save updated object in DB
				daoCar.save(carToEdit);
				// go to the list page
				setResponsePage(ListCarPage.class);
			}
		};

		// add form fields
		form.add(modelField);
		form.add(colorField);
		form.add(priceField);

		// add buttons
		form.add(new Button("saveLink"));
		form.add(new Link<Car>("cancelLink") {
			private static final long serialVersionUID = -1521748836027504873L;

			@Override
			public void onClick() {
				setResponsePage(ListCarPage.class);
			}
		});
		// add form to the page
		add(form);

		// add special component which will allow to display "validation errors"
		// and feedback messages
		FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		add(feedbackPanel);
	}

}
